import { CommonModule } from "@angular/common";
import { Component, Injectable, resource, signal } from "@angular/core";
import { type Signal } from "@angular/core";

type User = { id: string; name: string; email: string };

@Injectable({ providedIn: "root" })
export class UserResourceService {
  // 假设的 getUserId 实现（实际项目中可能来自路由参数或服务）
  private getUserId(): Signal<string> {
    return signal("default-user-id");
  }

  userId: Signal<string> = this.getUserId();

  userResource = resource<User, User>({
    defaultValue: { id: this.userId(), name: "", email: "aa@aa.com" },
    loader: async ({ params, abortSignal }): Promise<User> => {
      try {
        const response = await fetch(
          `https://api.example.com/users/${params.id}`,
          {
            signal: abortSignal,
          },
        );

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        return (await response.json()) as User;
      } catch (error) {
        if (error instanceof Error && error.name === "AbortError") {
          console.log("Request was aborted due to params change");
        }
        throw error; // 重新抛出错误供资源层处理
      }
    },
  });
}

// 在组件中使用示例
// @Component({
//   standalone: true,
//   imports: [CommonModule],
//   template: `
//     @if (userResourceService.userResource.isLoading()) {
//       <p>Loading user...</p>
//     }
//     @if (userResourceService.userResource.error(); as error) {
//       <div>Error: {{ error }}</div>
//     }
//     @if (userResourceService.userResource.value(); as user) {
//       <div>
//         <h2>{{ user.name }}</h2>
//         <p>Email: {{ user.email }}</p>
//       </div>
//     }

//     <div
//       *ngIf="globalThis.Math.random() > 0.5; then thenBlock; else elseBlock"
//     ></div>
//     <ng-template #thenBlock
//       >Content to render when condition is true.</ng-template
//     >
//     <ng-template #elseBlock
//       >Content to render when condition is false.</ng-template
//     >
//   `,
// })
// export class UserComponent {
//   globalThis = globalThis;

//   constructor(public userResourceService: UserResourceService) {} // 暴露给模板
// }
